package db

import (
	"gitee.com/Cookie_XiaoD/go-filestore-server/db/entities"
	"gitee.com/Cookie_XiaoD/go-filestore-server/db/mysql"
)

//AddUserFileInfo 添加用户文件信息
func AddUserFileInfo(entity *entities.AddUserFileEntity) bool {
	stmtOut, err := mysql.DBConn().Prepare("INSERT IGNORE INTO tbl_user_file(user_name,file_hash,file_size,file_name) VALUES(?,?,?,?)")
	defer stmtOut.Close()
	if err != nil {
		return false
	}

	_, err = stmtOut.Exec(entity.UserName, entity.FileHash, entity.FileSize, entity.FileName)
	if err != nil {
		return false
	}
	return true
}

//GetUserFileByUserName 根据用户名获取用户文件
func GetUserFileByUserName(userName string, limit int) ([]*entities.QueryUserFileEntity, error) {
	stmtout, err := mysql.DBConn().Prepare("SELECT user_name,file_hash,file_size,file_name,upload_at,last_update,status FROM tbl_user_file WHERE user_name=? " +
		"LIMIT ?")
	defer stmtout.Close()
	if err != nil {
		return nil, err
	}
	rows, err := stmtout.Query(userName, limit)
	if err != nil {
		return nil, err
	}
	results := []*entities.QueryUserFileEntity{}
	for rows.Next() {
		r := &entities.QueryUserFileEntity{}
		err := rows.Scan(&r.UserName, &r.FileHash, &r.FileSize, &r.FileName, &r.UploadAt, &r.LastUpdated, &r.Status)
		if err != nil {
			break
		}
		results = append(results, r)
	}
	return results, nil
}
